package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
public class ThreadLocalExampleService {

    // 初始化ThreadLocal变量，初始值为0
    private final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    // 模拟多线程操作
    private final ExecutorService executorService = Executors.newFixedThreadPool(3);

    public void incrementThreadLocalValue() {
        int currentValue = threadLocal.get(); // 获取当前线程的ThreadLocal值
        threadLocal.set(currentValue + 1); // 增加ThreadLocal值
        log.info("当前线程 [{}] 的 ThreadLocal 值为: {}", Thread.currentThread().getName(), threadLocal.get());
    }

    public void removeThreadLocalValue() {
        threadLocal.remove(); // 移除ThreadLocal值
        log.info("当前线程 [{}] 的 ThreadLocal 值已移除", Thread.currentThread().getName());
    }

    // 模拟多线程环境下的操作
    public void simulateThreadLocalUsage() {
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> {
                incrementThreadLocalValue(); // 每个线程增加ThreadLocal值
                try {
                    Thread.sleep(1000); // 模拟一些延迟
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                removeThreadLocalValue(); // 每个线程移除ThreadLocal值
            });
        }
    }
}
